import json
from datetime import datetime, timedelta, timezone
import matplotlib.pyplot as plt

class Data:
    def __init__(self , time , image_id , device_id):
        self.time = time
        self.image_id = image_id
        self.device_id = device_id

sends:list[Data] = list()
receives:list[Data] = list()
def peel_send(origin:str):
    aa = origin.split("------")
    time = aa[0].strip()
    info = aa[1].strip()
    image = json.loads(str(info).strip())
    image_data = image['data']['data']
    data = Data(time, image_data['image_id'],image_data['device_id'])
    sends.append(data)

def peel_receive(origin:str):
    aa = origin.split("------")
    time = aa[0].strip()
    info = aa[1].strip()
    image = json.loads(str(info).strip())
    image_data = image['data']
    data = Data(time, image_data['image_id'],image_data['device_id'])
    receives.append(data)

def peel_data(text , is_send):
    if text != "":
        text = text.replace("\'","\"")
        if is_send:
            peel_send(text)
        else:
            peel_receive(text)


def read_file(file_path, is_send):
    file = open( file_path , encoding='utf-8')
    # 此时只读取了一行
    pre = file.readline()
    pre = pre.replace("\n", "")

    peel_data(pre, is_send)

    while pre:
        next_line = file.readline()
        next_line = next_line.replace("\n", "")
        peel_data(next_line, is_send)
        pre = next_line
    file.close()


read_file('send.txt' , True)
read_file('receive.txt' , False)

print(f"----sends: {len(sends)}")
print(f"----receives: {len(receives)}")

def time_filter(time1, time2):
    receiveTime = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S.%f')
    sendTime = datetime.strptime(time2, '%Y-%m-%d %H:%M:%S.%f')
    timeGap = (receiveTime - sendTime)
    return timeGap.seconds


send_index = 0
receive_index = 0

time_axis = list()
gap_axis = list()
for i in range(0, len(sends)):
    if send_index < len(sends):
        send_item = sends[send_index]
    if receive_index < len(receives):
        receive = receives[receive_index]
    if send_item.image_id == receive.image_id and send_item.device_id == receive.device_id:
        receive_time = datetime.strptime(receive.time, '%Y-%m-%d %H:%M:%S.%f')
        send_time = datetime.strptime(send_item.time, '%Y-%m-%d %H:%M:%S.%f')
        gap = (receive_time - send_time)

        time_axis.append(receive.time)
        gap_axis.append(gap.seconds)

        print(f"----send_index: {send_index}--{receive_index}: gap: {gap}-----{receive_time}, send_time:{send_time}----")
        send_index += 1
        receive_index += 1
    else:
        send_index += 1


# plt.plot(time_axis, gap_axis, marker='o')  # 使用圆圈标记
# plt.xlabel('Time (s)')
# plt.ylabel('Data')
# plt.title('Data over Time')
# plt.grid(True)
# plt.show()




